<?php
namespace app\we\controller;
use think\Controller;
use think\helper\Time;


class Feed extends Controller{


    public function _initialize(){

        $this->rank=array(1=>'好评',2=>'中评',3=>'差评');
        $this->rankico=array(1=>"/:strong",2=>'/:,@f',3=>"/:weak");
      
    }

    public function index($openid=""){
      $fans=model('WeFans')->info($openid);
      $we=model('We')->info($fans['appid']);
      if(request()->isPost()){
        $data=input('post.');
        // 数据有效性
        
        $data['aid']=$fans['aid'];
        $data['appid']=$fans['appid'];
        $data['nickname']=$fans['nickname'];
        //计算当日反馈数量
        $today = Time::today();
        $today_total=db('WeFeed')->where('aid',$data['aid'])->where('shopid',$data['shopid'])->where('create_time','between time',$today)->count();
        $data['today_um']=$data['shopid'].'-'.($today_total+1);
        $today_my_total=db('WeFeed')->where('openid',$data['openid'])->where('shopid',$data['shopid'])->where('create_time','between time',$today)->count();
        if ($today_my_total>0) $this->error('您今天已经反馈，谢谢');
        $feed_id=model('we/WeFeed')->editData($data);
        
        if ($feed_id){
        //优先发送客服消息，失败后发送模板消息
            $admins=model('we/WeFans')->getAdmins($fans['appid']);
            $shop=model('admin/AdminShop')->info($data['shopid']);
            $message_first=$shop['title']."第".($today_total+1).'条客情：';
            $message_keyword1=$fans['id']."号顾客".$fans['nickname']." - 评价".$data['target'];
            $message_keyword2=date('Y-m-d H:i:s',time());
            $message_remark=$fans['nickname'].':'.$data['content'];
            

            foreach ($admins as $key => $admin) {
               $url=my_domain().url('chatAdmin',['feed_id'=>$feed_id,'admin_openid'=>$admin['openid']]);
               $reply=[
                'template_id'=>'ONti3SvUva-CJ670lNkhfsgGtQnwcoKjEpY-B-1oMK0',
                'url'=>$url,
                'data'=>[
                'first'=>['value'=>$message_first],
                'keyword1'=>['value'=>$message_keyword1],
                'keyword2'=>['value'=>$message_keyword2],
                'remark'=>['value'=>$message_remark]
                ]
                ];
               template_message($admin['openid'],$reply);
            }
            custom_message($fans['openid'],'您的反馈我们已经收到，谢谢！么么哒');
            if ($we['feed_card']){
               $card_message=['msgtype'=>'wxcard','wxcard'=>['card_id'=>$we['feed_card']]];
               custom_message($fans['openid'],$card_message);
            }

            $this->success('成功反馈',$we['feed_url']);
        }
        $this->error('反馈失败');

      }else{
        $shops=my_select('AdminShop','id','title',['aid'=>$fans['aid']]); 
        
        $this->assign('openid',$openid);
        $this->assign('shops',$shops);
        return $this->fetch();
      }
  
       
    }

    public function chatAdmin($feed_id="",$admin_openid=''){

      $feed=model('WeFeed')->info($feed_id);
      if (!$feed || !$admin_openid) die('回话已经过期');
      $fans=model('we/WeFans')->info($feed['openid']); //获取了使用者
      $admin=model('we/WeFans')->info($admin_openid); //获取了客服
      if (!$admin['admin']) die('未登陆');
     

      if(request()->isPost()){
        $data=input('post.');
        // 数据有效性
        
        $data['aid']=$fans['aid'];
        $data['feed']=$data['feed_id'];
        $data['nickname']=$fans['nickname'];
        $data['admin_openid']=$admin['openid'];
        $data['admin_nickname']=$admin['nickname'];
        $data['type']=1;
       
       
        $chat_id=model('we/WeFeedChat')->editData($data);
        
        if ($chat_id){
            
            $first=mb_substr($data['content'],0,1); 
           
              if ($first=='卡') {
                $card_id=str_replace('卡',"",$data['content']);
                $card=model('we/weCard')->info($card_id);
                $message=['msgtype'=>'wxcard','wxcard'=>['card_id'=>$card['card_id']]];
                $message_error=custom_message($admin['openid'],$message);   
              }else{
                $message_first="你的反馈有了新的回复：";
                $message_keyword1="留言(".$feed['id']."):".$feed['content'];
                $message_keyword2=date('Y-m-d H:i:s',time());
                $message_remark=$data['admin_nickname'].':'.$data['content'];
                $url=my_domain().url('chat',['feed_id'=>$feed_id,'openid'=>$fans['openid'],'type'=>0]);
                $reply=[
                  'template_id'=>'ONti3SvUva-CJ670lNkhfsgGtQnwcoKjEpY-B-1oMK0',
                  'url'=>$url,
                  'data'=>[
                  'first'=>['value'=>$message_first],
                  'keyword1'=>['value'=>$message_keyword1],
                  'keyword2'=>['value'=>$message_keyword2],
                  'remark'=>['value'=>$message_remark]
                  ]
                ];
                $message_error=template_message($admin['openid'],$reply); 
            }
            
            $this->success('成功反馈'.$message_error,url('chat',['feed_id'=>$feed_id,'openid'=>$openid,'admin_openid'=>$admin_openid,'type'=>$type]));
        }
        $this->error('反馈失败');

      }else{

        //加载扫码和卡券
          $cards=db('WeCard')->where('appid',$fans['appid'])->select();
          $cards_info='卡券列表：(卡1：发1号卡券给粉丝)';
          foreach ($cards as $key => $card) {
              $cards_info.="</br>".$card['id']."号卡券：".$card['title'];
          }
          $fnas_cards=get_fans_card($fans['appid'],$fans['openid']);
          $cards_info.='</br>该粉丝拥有';
          foreach ($fnas_cards['card_list'] as $key => $fnas_card) {
             $this_card= db('WeCard')->where('card_id',$fnas_card['card_id'])->find();
             $cards_info.="</br>".$this_card['id']."号卡券：".$this_card['title'];
          }
          //扫码记录
          $scans=model('WeSceneScan')->where('openid',$fans['openid'])->where('qrcode_type',1)->order('create_time desc')->limit(5)->select();
          $scans_info="</br>扫码记录";
          foreach ($scans as $key => $scan) {
             $scans_info.="</br>".date('m-d H',$scan['create_time'])."扫描".$scan['qrcode'];
          }
      

        //加载对话内容
        $chats=db('WeFeedChat')->where('feed',$feed_id)->select();
          if ($chats){
            foreach ($chats as $key => &$chat) {
                $admin=model('we/WeFans')->info($chat['admin_openid']);
                if ($chat['type']==1){
                  $chat['headimgurl']=$admin['headimgurl'];
                }else{
                  $chat['headimgurl']=$fans['headimgurl'];
                }
            }
        }

        $this->assign('feed',$feed);
        $this->assign('chats',$chats);
        $this->assign('fans',$fans);
        $this->assign('admin_openid',$admin_openid);
       
        if (isset($cards_info))$this->assign('cards_info',$cards_info);
        if (isset($scans_info))$this->assign('scans_info',$scans_info);
      
        return $this->fetch();
      }
  
       
    }


    public function chat($feed_id="",$openid=''){

      $feed=model('WeFeed')->info($feed_id);
      if (!$feed) die('回话已经过期');
      if ($openid and $openid!=$feed['openid']) die('无权回复');
      $fans=model('we/WeFans')->info($feed['openid']); //获取了使用者
      
      //加载对话内容
      $chats=db('WeFeedChat')->where('feed',$feed_id)->select();
          if ($chats){
            foreach ($chats as $key => &$chat) {
                $admin=model('we/WeFans')->info($chat['admin_openid']);
                if ($chat['type']==1){
                  $chat['headimgurl']=$admin['headimgurl'];
                }else{
                  $chat['headimgurl']=$fans['headimgurl'];
                }
            }
      }

      if(request()->isPost()){
        $data=input('post.');
        // 数据有效性
        
        $data['aid']=$fans['aid'];
        $data['feed']=$data['feed_id'];
        $data['nickname']=$fans['nickname'];
        $data['admin_openid']=$admin['openid'];
        $data['admin_nickname']=$admin['nickname'];
        $data['type']=0;
       
       
        $chat_id=model('we/WeFeedChat')->editData($data);
        
        if ($chat_id){
           
            $message_first=$fans['id']."号顾客回复了客情：";
            $message_keyword1=$fans['id']."号顾客 - 评价".$feed['target'];
            $message_keyword2=date('Y-m-d H:i:s',time());
            $message_remark=$fans['nickname'].':'.$data['content'];
            $url=my_domain().url('chat',['feed_id'=>$feed_id,'admin_openid'=>$admin['openid'],'type'=>1]);
            $reply=[
              'template_id'=>'ONti3SvUva-CJ670lNkhfsgGtQnwcoKjEpY-B-1oMK0',
              'url'=>$url,
              'data'=>[
              'first'=>['value'=>$message_first],
              'keyword1'=>['value'=>$message_keyword1],
              'keyword2'=>['value'=>$message_keyword2],
              'remark'=>['value'=>$message_remark]
              ]
            ];
           $message_error=template_message($admin['openid'],$reply);
           $this->success('成功反馈'.$message_error,url('chat',['feed_id'=>$feed_id,'openid'=>$openid,'admin_openid'=>$admin_openid,'type'=>$type]));
        }
        $this->error('反馈失败');

      }else{
      
        $this->assign('feed',$feed);
        $this->assign('chats',$chats);
        $this->assign('fans',$fans);
       
       
        return $this->fetch();
      }
  
       
    }




   
}